﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Specialized;

namespace LifeInSharePoint.Common
{
    public class SPQueryStringHelper
    {
        #region Public Methods

        /// <summary>
        /// The get query string item.
        /// </summary>
        /// <param name="queryString">
        /// The query string.
        /// </param>
        /// <param name="keyName">
        /// The key name.
        /// </param>
        /// <param name="defaultValue">
        /// The default value.
        /// </param>
        /// <returns>
        /// The get query string item.
        /// </returns>
        public static int GetQueryStringItem(NameValueCollection queryString, string keyName, int defaultValue)
        {
            int returnValue = defaultValue;

            try
            {
                if (queryString[keyName] != null)
                {
                    returnValue = int.Parse(queryString[keyName].ToString());
                }
            }
            catch (Exception ex)
            {
                // LoggingHelper.LogEvent(String.Format(@"Exception: module='{0}', message='{1}', stackTrace='{2}'", System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message, ex.StackTrace), true, EventLogEntryType.Error, false, null, false, null);
            }
            finally
            {
            }

            // Debug.WriteLine(String.Format(@"Returnvalue for key '{0}'='{1}'.", keyName, returnValue));
            return returnValue;
        }

        /// <summary>
        /// The get query string item.
        /// </summary>
        /// <param name="queryString">
        /// The query string.
        /// </param>
        /// <param name="keyName">
        /// The key name.
        /// </param>
        /// <param name="defaultValue">
        /// The default value.
        /// </param>
        /// <returns>
        /// The get query string item.
        /// </returns>
        public static string GetQueryStringItem(NameValueCollection queryString, string keyName, string defaultValue)
        {
            string returnValue = defaultValue;

            try
            {
                if (queryString[keyName] != null)
                {
                    returnValue = queryString[keyName].ToString();
                }
            }
            catch (Exception ex)
            {
                // LoggingHelper.LogEvent(String.Format(@"Exception: module='{0}', message='{1}', stackTrace='{2}'", System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message, ex.StackTrace), true, EventLogEntryType.Error, false, null, false, null);
            }
            finally
            {
            }

            // Debug.WriteLine(String.Format(@"Returnvalue for key '{0}'='{1}'.", keyName, returnValue));
            return returnValue;
        }

        /// <summary>
        /// Sets the specified parameter to the specified value in the specified URL
        /// </summary>
        /// <param name="url">
        /// The URL with the query string
        /// </param>
        /// <param name="parameterName">
        /// The name of the query string parameter
        /// </param>
        /// <param name="parameterValue">
        /// The value to the set the parameter to
        /// </param>
        /// <param name="preserveQueryString">
        /// Whether to preserve the rest of the query string
        /// </param>
        /// <returns>
        /// The new URL
        /// </returns>
        public static string SetParameterInQueryString(
            string url, string parameterName, string parameterValue, bool preserveQueryString)
        {
            if (preserveQueryString)
            {
                if (url.IndexOf(parameterName + "=", StringComparison.CurrentCultureIgnoreCase) >= 0)
                {
                    //-------Added by Saurin.Khamar, Earlier expression replace querystring from position of searching parameter to end of string--
                    return Regex.Replace(
                        url, parameterName + "(?:=([^&]*))", parameterName + "=" + parameterValue, RegexOptions.IgnoreCase);
                    //-------Added new and commented previous by Saurin.Khamar--------------//
                    //return Regex.Replace(
                    //    url, parameterName + "=[^%]*", parameterName + "=" + parameterValue, RegexOptions.IgnoreCase);
                }
                else if (url.IndexOf('?') >= 0)
                {
                    return url + "&" + parameterName + "=" + parameterValue;
                }
                else
                {
                    return url + "?" + parameterName + "=" + parameterValue;
                }
            }
            else
            {
                int queryStringIndex = url.IndexOf('?');
                if (queryStringIndex >= 0)
                {
                    url = url.Substring(0, queryStringIndex);
                }

                return url + "?" + parameterName + "=" + parameterValue;
            }
        }

        /// <summary>
        /// Sets the specified parameter to the specified value in the specified URL
        /// </summary>
        /// <param name="url">
        /// The URL with the query string
        /// </param>
        /// <param name="parameterName">
        /// The name of the query string parameter
        /// </param>
        /// <param name="parameterValue">
        /// The value to the set the parameter to
        /// </param>
        /// <param name="preserveQueryString">
        /// Whether to preserve the rest of the query string
        /// </param>
        /// <returns>
        /// The new URL
        /// </returns>
        public static string RemoveParameterFromQueryString(
            string url, string parameterName)
        {
            if (url.IndexOf(parameterName + "=", StringComparison.CurrentCultureIgnoreCase) >= 0)
            {
                return Regex.Replace(
                    url, parameterName + "(?:=([^&]*))", String.Empty, RegexOptions.IgnoreCase);
            }
            else
            {
                return url;
            }
        }
        #endregion
    }
}